package output

import (
	"gitee.com/krio/ginc/example/core/exerr"
	"github.com/gin-gonic/gin"
)

const ResponseCtxKey = "ctx_api_output"

// ResponseManager 策略管理器
type ResponseManager struct {
	strategies map[string]ResponseFormatter
}

// NewResponseManager 创建策略管理器实例
func NewResponseManager() *ResponseManager {
	return &ResponseManager{
		strategies: map[string]ResponseFormatter{
			OutputDefault: &DefaultFormatter{},
			OutputAdmin:   &AdminFormatter{},
			OutputNot:     &NotFormatter{},
		},
	}
}

// 全局策略管理器实例
var responseManager = NewResponseManager()

// Response 根据输出类型格式化响应
func Response(ctx *gin.Context, outputType string, resp exerr.IExerr) {
	if outputType == "" {
		outputType = ctx.GetString(ResponseCtxKey)
	}
	formatter := responseManager.GetFormatter(outputType)
	formatter.Format(ctx, resp)
}

// GetFormatter 获取指定类型的格式化策略
func (rm *ResponseManager) GetFormatter(outputType string) ResponseFormatter {
	if formatter, exists := rm.strategies[outputType]; exists {
		return formatter
	}
	return rm.strategies["default"]
}

// ResponseFormatter 响应格式化策略接口
type ResponseFormatter interface {
	Format(ctx *gin.Context, resp exerr.IExerr)
}
